package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        log.info("拦截到请求: {}",request.getRequestURI());
        //chain.doFilter(request,response);
        String requestURI = request.getRequestURI();
        String[] uris =new String[]{
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/common/**",//放行common下的操作，便于测试
                "/user/sendMsg",
                "/user/login"
        };
        Boolean check=check(requestURI,uris);
        if(check){
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        //判断员工登录状态
        Long currentId = (Long) request.getSession().getAttribute("employee");
        if(currentId!=null){
            BaseContext.setCurrentId(currentId);
            filterChain.doFilter(request,response);
            return;
        }
        //判断用户登录状态
        Long userId = (Long) request.getSession().getAttribute("user");
        if(userId!=null){
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        //如果未登录，响应NOTLOGIN数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     *
     * @param requestURI 获取到的请求路径
     * @param uris 放行的路径
     * @return true：需要放行，false：不放行
     */
    private Boolean check(String requestURI, String[] uris) {
        for (String uri : uris) {
            boolean match = PATH_MATCHER.match(uri, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
